package com.kexio.core.web.config;

import com.kexio.core.properties.CoreProperties;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.servers.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Swagger API文档配置
 * 
 * @author Kexio Team
 * @since 1.0.0
 */
@Configuration
@EnableConfigurationProperties(CoreProperties.class)
@ConditionalOnProperty(prefix = "kexio.core.web.swagger", name = "enabled", havingValue = "true", matchIfMissing = true)
public class SwaggerConfig {
    
    private static final Logger log = LoggerFactory.getLogger(SwaggerConfig.class);
    
    private final CoreProperties coreProperties;
    
    public SwaggerConfig(CoreProperties coreProperties) {
        this.coreProperties = coreProperties;
        log.info("==> Kexio Swagger配置已启用");
    }
    
    @Bean
    public OpenAPI customOpenAPI() {
        CoreProperties.Web.Swagger swaggerProps = coreProperties.getWeb().getSwagger();
        
        return new OpenAPI()
            .info(new Info()
                .title(swaggerProps.getTitle())
                .version(swaggerProps.getVersion())
                .description(swaggerProps.getDescription())
                .contact(new Contact()
                    .name("Kexio Team")
                    .email("support@kexio.com")
                    .url("https://kexio.com"))
                .license(new License()
                    .name("Apache License 2.0")
                    .url("https://www.apache.org/licenses/LICENSE-2.0")))
            .addServersItem(new Server()
                .url("http://localhost:8080")
                .description("开发环境"))
            .addServersItem(new Server()
                .url("https://api.kexio.com")
                .description("生产环境"))
            // 添加JWT认证
            .addSecurityItem(new SecurityRequirement().addList("Bearer Authentication"))
            .components(new io.swagger.v3.oas.models.Components()
                .addSecuritySchemes("Bearer Authentication",
                    new SecurityScheme()
                        .type(SecurityScheme.Type.HTTP)
                        .scheme("bearer")
                        .bearerFormat("JWT")
                        .description("请输入JWT Token")));
    }
}
